<script>
import pubsub from "pubsub-js"
export default {
  name: "MyItem",
  props:['todoObj'],
  computed:{
    checked(){
      return this.todoObj.done;
    }
  },
  methods:{
    dataChanged(id){
      this.$bus.$emit('todoObjChangeDone', id);
    },
    deleteObj(id){
      console.log('消息发布实现删除');
      pubsub.publish('deleteTodo', id);
      //this.$bus.$emit('deleteTodo', id);
    },
    editeObj(todoObj){
      if(todoObj.hasOwnProperty('isEditing')){
        todoObj.isEditing = true
      }else{
        this.$set(todoObj,'isEditing',true)
      }

      this.$nextTick(function (){
        //下一次dom更新后，执行该函数，通常用于隐藏的input无法触发获取焦点事件，
        // 当函数里面同时进行了展示原来隐藏的元素和获得焦点的两个操作时，如果不用$nextTick，会导致获得焦点无法实现，
        // 因为在本次函数实行结束前，元素还是隐藏的吗，对隐藏的元素获取焦点是不合逻辑的
        this.$refs.inputName.focus()
      })

      //todoObj.isEditing = true;
    },
    //失去焦点时才取改
    handleBlur(todoObj,e){
      todoObj.isEditing = false;
      if(!e.target.value.trim()){
        alert('输入不能为空');
        return;
      }
      this.$bus.$emit('editeName',todoObj.id,e.target.value)
    }
  }
}
</script>

<template>
  <div>
    <li>
      <label>
        <input type="checkbox" :checked="checked" @change="dataChanged(todoObj.id)"/>
        <span v-show="! todoObj.isEditing">{{ todoObj.name }}</span>
        <input  type="text"
                v-show="todoObj.isEditing"
               :value="todoObj.name"
               @blur="handleBlur(todoObj,$event)"
                ref="inputName">
      </label>
      <button class="btn btn-danger" @click="deleteObj(todoObj.id)">删除</button>
      <button v-show="! todoObj.isEditing" class="btn btn-edite" @click="editeObj(todoObj)">编辑</button>
    </li>
  </div>


</template>

<style scoped>

li{
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:hover button {
  float: right;
  display: block;
  margin-top: 3px;
}
li:hover{
  background-color: #cccccc;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

</style>